package gradle.mybatis.common.interceptor;

import gradle.common.core.annotation.SnowflakeId;
import gradle.mybatis.common.utils.SnowflakeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * insert 语句 主键ID 设置雪花算法
 *
 * @author 1141193930@qq.com
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Slf4j
public class SnowflakeIdInterceptor implements Interceptor {

    /**
     * 主键ID字段名称
     */
    private final String ID_NAME = "id";
    /**
     * mybatis 变量参数前缀
     */
    private final String MYBATIS_PARAM_NAME = "param";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        if (ms.getSqlCommandType().equals(SqlCommandType.INSERT) && parameterObject != null) {
            if (parameterObject instanceof java.util.Map<?, ?> paramMap) {
                // 多参数情况，遍历 map 的 value
                Set<?> keys = paramMap.keySet();
                for (Object key : keys) {
                    Object paramValue = paramMap.get(key);
                    if (((String) key).startsWith(MYBATIS_PARAM_NAME)) {
                        //set value
                        if (paramValue instanceof Collection) {
                            processBatchInsert((Collection<?>) paramValue);
                        } else {
                            processSingleInsert(paramValue);
                        }
                    }
                }
            } else {
                // 普通单个实体
                processSingleInsert(parameterObject);
            }
        }
        return invocation.proceed();
    }


    /**
     * 处理批量插入，为集合中的每个实体对象设置雪花ID
     */
    private void processBatchInsert(Collection<?> collection) {
        collection.forEach(entity -> Optional.ofNullable(entity).ifPresent(this::setSnowflakeIdForEntity));
    }

    /**
     * 处理单条插入
     */
    private void processSingleInsert(Object parameterObject) {
        Optional.ofNullable(parameterObject).ifPresent(this::setSnowflakeIdForEntity);
    }

    /**
     * 为单个实体对象设置雪花ID（提取你原有的逻辑）
     */
    private void setSnowflakeIdForEntity(Object entity) {
        //查询是否有主键ID字段
        Field idField = ReflectionUtils.findField(entity.getClass(), ID_NAME);
        if (Objects.nonNull(idField)) {
            SnowflakeId annotation = idField.getAnnotation(SnowflakeId.class);
            if (Objects.nonNull(annotation)) {
                ReflectionUtils.makeAccessible(idField);
                ReflectionUtils.setField(idField, entity, SnowflakeUtils.getSnowflake().nextId());
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }

}